<template>
  <el-dialog
    class="theme"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="上级" prop="pid">
        <el-select v-model="form.pid" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :disabled="item.state != 1"
            :label="getOriginName(item.title, item.spacer)"
            :value="item.id"
          >
            <span v-html="item.title"></span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="title">
        <el-input v-model.trim="form.title" />
      </el-form-item>
      <el-form-item label="标识" prop="name">
        <el-input v-model.trim="form.name" />
      </el-form-item>
      <el-form-item v-if="false" label="权限" prop="">
        <el-checkbox v-model="checkedAll" @change="setCheckedAll">
          全选选中
        </el-checkbox>
        <el-checkbox
          v-model="expandedAll"
          @change="setExpandedAll(permissionData)"
        >
          全部展开
        </el-checkbox>
        <el-tree
          ref="tree"
          v-loading="loading"
          :data="permissionData"
          :default-checked-keys="checkedKeys"
          node-key="id"
          :props="defaultProps"
          show-checkbox
          @check="treeCheck"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-radio-group v-model="form.state">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit, getPermission } from '@/api/roleManagement'

  export default {
    name: 'UserManagementEdit',
    data() {
      return {
        form: {
          state: 1,
        },
        roleList: [],
        rules: {
          pid: [{ required: true, trigger: 'change', message: '请选择上级' }],
          title: [{ required: true, trigger: 'blur', message: '请输入名称' }],
          name: [{ required: true, trigger: 'blur', message: '请输入标识' }],
          state: [{ required: true, trigger: 'blur', message: '请选择状态' }],
        },
        title: '',
        dialogFormVisible: false,
        permissionData: [],
        defaultProps: {
          children: 'children',
          label: 'title',
        },
        loading: false,
        checkedAll: false,
        expandedAll: false,
        checkedKeys: [],
      }
    },
    // watch: {
    //   'form.pid': {
    //     handler(val) {
    //       if (val) this.getPermission()
    //     },
    //     // 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法
    //     immediate: true,
    //   },
    // },
    methods: {
      showEdit(roleList, row) {
        this.permissionData = []
        this.checkedKeys = []
        this.checkedAll = false
        this.expandedAll = false
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
          this.form.title = this.getOriginName(row.title, row.spacer)
        }
        if (roleList) this.roleList = roleList
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      save() {
        // 获取权限选中的状态
        // let checkedKeys = this.$refs.tree.getCheckedKeys()
        // let HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
        // checkedKeys = checkedKeys.concat(HalfCheckedKeys)
        let checkedKeys = []
        this.form.checkedKeys = checkedKeys
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            const { message } = await doEdit(this.form)
            this.$baseMessage(
              message,
              'success',
              false,
              'vab-hey-message-success'
            )
            this.$emit('fetch-data')
            this.close()
          }
        })
      },
      getOriginName(name, str_rep = '&nbsp;') {
        return name.replace(str_rep, '').trim()
      },
      async getPermission() {
        this.loading = true
        const { data } = await getPermission({
          pid: this.form.pid,
          role_id: this.form.id,
        })
        this.permissionData = data.permission
        this.checkedKeys = data.checked
        this.loading = false
      },
      treeCheck(data, obj) {
        console.log(data, obj)
      },
      // 全部选中
      setCheckedAll() {
        if (this.checkedAll) {
          //全选
          this.$refs.tree.setCheckedNodes(this.permissionData)
        } else {
          //取消选中
          this.$refs.tree.setCheckedKeys([])
        }
      },
      // 全部展开
      setExpandedAll(data) {
        let that = this
        data.forEach((el) => {
          that.$refs.tree.store.nodesMap[el.id].expanded = that.expandedAll
          el.children && el.children.length > 0
            ? that.setExpandedAll(el.children)
            : '' // 子级递归
        })
      },
    },
  }
</script>
